package com.c2b.algorithm.leetcode.jzoffer;

import java.util.ArrayList;

/**
 * 从尾到头打印链表
 * <p>输入一个链表的头节点，按链表从尾到头的顺序返回每个节点的值（用数组返回）。</p>
 *
 * @author c2b
 * @since 2023/3/7 11:32
 */
public class JzOffer0006PrintListFromTailToHead {
    /**
     * 从尾到头打印链表
     *
     * @param listNode 头节点
     * @return 按链表从尾到头的顺序返回每个节点的值
     */
    public ArrayList<Integer> printListFromTailToHead(final ListNode listNode) {
        final ArrayList<Integer> list = new ArrayList<>();
        if (listNode != null) {
            printListFromTailToHead(list, listNode.next);
            list.add(listNode.val);
        }
        return list;
    }

    private void printListFromTailToHead(final ArrayList<Integer> list, final ListNode listNode) {
        if (listNode != null) {
            printListFromTailToHead(list, listNode.next);
            list.add(listNode.val);
        }
    }

    public ArrayList<Integer> printListFromTailToHead2(final ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        ListNode tmp = listNode;
        while (tmp != null) {
            list.add(0, tmp.val);
            tmp = tmp.next;
        }
        return list;
    }


    public static void main(final String[] args) {
        final ListNode listNode = new ListNode(1);
        listNode.next = new ListNode(3);
        listNode.next.next = new ListNode(2);
        final JzOffer0006PrintListFromTailToHead jzOffer0006PrintListFromTailToHead = new JzOffer0006PrintListFromTailToHead();
        final ArrayList<Integer> integers = jzOffer0006PrintListFromTailToHead.printListFromTailToHead(listNode);
        for (Integer integer : integers) {
            System.out.println(integer);
        }
    }

}
